﻿using Client.ICommandNotify;
using Client.IConfiguration;
using Client.Models;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Media;

namespace Client.ViewModel
{
    public class SqlQueryViewModel : ICommandNotify.NotifyBase
    {
        public System.Windows.Controls.RichTextBox richTextBox;

        SqlServer.DbContext dbContext = HelpTools.IOC.Getobject<SqlServer.DbContext>();
        public SqlQueryViewModel()
        {
            QueryTableCommand = new Command(QueryTableDoExecute, QueryTableCanExecute);
            Query = new Command(QueryDoExecute, QueryCanExecute);
            OpenFile = new Command(OpenFileDoExecute, OpenFileCanExecute);
            OpenFileDoExecute(new object());
        }

        private bool OpenFileCanExecute()
        {
            return true;
        }

        private void OpenFileDoExecute(object obj)
        {
            if (FileList == null) FileList = new object();
            string selectedFolderPath= "D:\\Desktop\\智能制造\\运维SQL脚本";
            // 创建 FolderBrowserDialog 实例
           
            //using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog())
            //{
            //    // 设置对话框的标题
            //    folderBrowserDialog.Description = "选择文件夹";
            //    // 设置对话框的行为
            //    folderBrowserDialog.ShowNewFolderButton = true; // 是否显示“新建文件夹”按钮
            //    // 显示对话框并获取用户选择的结果
            //    DialogResult result = folderBrowserDialog.ShowDialog();
            //    // 如果用户选择了文件夹，则显示文件夹路径
            //    if (result == System.Windows.Forms.DialogResult.OK && !string.IsNullOrWhiteSpace(folderBrowserDialog.SelectedPath))
            //    {
            //        selectedFolderPath = folderBrowserDialog.SelectedPath;
            //    }
            //}
            //  if (string.IsNullOrWhiteSpace(selectedFolderPath)) return;
                DirectoryInfo directoryInfo = new DirectoryInfo(selectedFolderPath);
               FileList= directoryInfo.GetFiles().Select(o =>
                {
                    return new
                    {
                        FileNameValue=o.Name,
                        FileName=o.FullName
                    };
                });
        }

        private bool QueryCanExecute()
        {
            return true;
        }

        private void QueryDoExecute(object obj)
        {
            if(string.IsNullOrWhiteSpace(Textselect))
            {
             WPFDevelopers.Minimal.Controls.MessageBox.Show("请输入查询语句", "消息", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                return;
            }
            ListTable= dbContext.Where(Textselect).DefaultView;
        }

        private bool QueryTableCanExecute()
        {
            return true;
        }

        private void QueryTableDoExecute(object obj)
        {
            var DbContext_ = HelpTools.IOC.Getobject<SqlServer.DbContext>();
            if(obj as string!=null)
            DbContext_.SqlConfigstr = obj as string;
            SurfaceList= DbContext_.Where("SELECT name AS DatabaseName FROM sys.databases").Select().Select(o =>
            {
                return new
                {
                    SurfaceName = o["DatabaseName"].ToString()
                };
            });
        }

        public Command QueryTableCommand { get; set; }
        public Command Query { get; set; }

        public Command OpenFile { get; set; }
        private DataView ListTable_;

        public DataView ListTable
        {
            get { return ListTable_; }
            set
            {
                ListTable_ = value;
                SetProperty(ref ListTable_, ListTable);
            }
        }

        private List<SetUpModel> DatabaseList_;

        public List<SetUpModel> DatabaseList
        {
            get {
                var IConfiguration_ = HelpTools.IOC.Getobject<IConfiguration.IConfigurationHelp>();
                    DatabaseList_=IConfiguration_.GetSetUpModel();
                return DatabaseList_; }
            set { DatabaseList_ = value;
                SetProperty(ref DatabaseList_, DatabaseList);
            }
        }
        private object SurfaceList_;

        public object SurfaceList
        {
            get { return SurfaceList_; }
            set { SurfaceList_ = value;
                SetProperty(ref DatabaseList_, DatabaseList);
            }
        }

        private Dictionary<string,string> myVar;

        public Dictionary<string,string> MyProperty
        {
            get {
                if(myVar == null||myVar.Count==0)
                {
                    myVar = new Dictionary<string, string>();
                    myVar.Add("SRBG_Project", "Data Source=192.168.100.6;Initial Catalog=SRBG_Project;User ID=sa;Password=asdw@122");
                    myVar.Add("SRBG_Material", "Data Source=192.168.100.6;Initial Catalog=SRBG_Material;User ID=sa;Password=asdw@122");
                    myVar.Add("SRBG_Revolve", "Data Source=192.168.100.6;Initial Catalog=SRBG_Revolve;Persist Security Info=True;User ID=sa;Password=asdw@122");
                    myVar.Add("SRBG_Basic", "Data Source=192.168.100.25;Initial Catalog=SRBG_Basic;User ID=pcwp;Password=pcwpasdw@123");
                    myVar.Add("SRBG_Equip", "Data Source=192.168.100.6;Initial Catalog=SRBG_Equip;User ID=sa;Password=asdw@122");
                    myVar.Add("SRBG_CBM", "Data Source=192.168.100.6;Initial Catalog=SRBG_CBM;User ID=sa;Password=asdw@122");
                    myVar.Add("SRBG_Tender", "Data Source=192.168.100.6;Initial Catalog=SRBG_Tender;User ID=sa;Password=asdw@122");
                }
                return myVar; }
            set { myVar = value; }
        }
        private string SurfaceValue_;

        public string SurfaceValue
        {
            get { return SurfaceValue_; }
            set {

                dbContext.SqlConfigstr = MyProperty[value];
                SurfaceValue_ = value; }
        }
        private string Textselect_;

        public string Textselect
        {
            get { return Textselect_; }
            set { Textselect_ = value; }
        }

        private object FileList_;

        public object FileList
        {
            get { return FileList_; }
            set { FileList_ = value;
                SetProperty(ref FileList_, FileList);
            }
        }
            // 定义 SQL 关键字
            List<string> sqlKeywords = new List<string>
            {
                "SELECT", "FROM", "WHERE", "INNER JOIN", "LEFT JOIN", "AND", "OR", "ORDER BY", "DISTINCT", "AS", "WITH (NOLOCK)", "GROUP BY", "HAVING","JOIN"
            };
        private string FileNameValue_;

        public string FileNameValue
        {
            get { return FileNameValue_; }
            set { FileNameValue_ = value;
                richTextBox.Document.Blocks.Clear();
                Paragraph paragraph = new Paragraph();
                //richTextBox.Document.Blocks.Add(paragraph);
                // 添加文本
                Textselect = File.ReadAllText(value);
                paragraph.Inlines.Add(new Run(Textselect));
                richTextBox.Document.Blocks.Add(paragraph);
                // 获取文档的起始指针
               // TextPointer contentStart = richTextBox.Document.ContentStart;
                // 查找并高亮关键字
                //foreach (var keyword in sqlKeywords)
                //{
                //    TextPointer currentPointer = contentStart;
                //    //遍历文档内容查找关键字
                //    int offset = 0;
                //    while (currentPointer != null && currentPointer.CompareTo(richTextBox.Document.ContentEnd) < 0)
                //    {
                //        TextPointer nextPointer = currentPointer.GetPositionAtOffset(keyword.Length);
                //        if (nextPointer == null) break; // 如果超出文档范围，退出循环
                //        // 查找关键字
                //        TextRange textRange = new TextRange(currentPointer, nextPointer);
                //        string text = textRange.Text;
                //        if (text != null && text.Contains(keyword))
                //        {
                //            //高亮关键字
                //            textRange.ApplyPropertyValue(TextElement.ForegroundProperty, new BrushConverter().ConvertFrom("#4594F0"));
                //            textRange.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
                //            offset += keyword.Length;
                //            currentPointer = currentPointer.GetPositionAtOffset(offset);
                //        }
                //        else
                //        {
                //          currentPointer = currentPointer.GetPositionAtOffset(offset + 1);
                //        }
                //            //移动到下一个位置
                //    }
                //}

                // 查找并设置注释部分的格式
                //string commentMarker = "--";
                //TextPointer commentPointer = contentStart;

                //while (commentPointer != null && commentPointer.CompareTo(richTextBox.Document.ContentEnd) < 0)
                //{
                //    // 查找注释
                //    TextRange textRange = new TextRange(commentPointer, commentPointer.GetPositionAtOffset(commentMarker.Length));
                //    string text = textRange.Text;
                //    if (text.Contains(commentMarker))
                //    {
                //        // 获取注释的结束位置
                //        TextPointer commentEndPointer = commentPointer.GetPositionAtOffset(text.Length);
                //        // 设置注释样式
                //        TextRange commentRange = new TextRange(commentPointer, commentEndPointer);
                //        commentRange.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Green);
                //        commentRange.ApplyPropertyValue(TextElement.FontStyleProperty, FontStyles.Italic);
                //    }
                //    // 移动到下一个位置
                //    commentPointer = commentPointer.GetPositionAtOffset(1);
                //}
            }
        }

    }
}
